/**
 * Copyright 2021 xpstem.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.xpstem.lelink.type;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * 2 byte data type.
 * @author billy zhang
 */
public class Data16 implements EV3Type  {

    private static final byte SIZE = 2;

    private int value;

    private Data16(int value) {
        setValue( value );
    }

    public void setValue(int value) {
        // TODO:
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static Data16 from(int value) {
        return new Data16(value);
    }

    public void writeTo(OutputStream outStream) throws IOException {
        outStream.write((byte)value);
        outStream.write((byte)value >> 8);
    }

    @Override
    public int size() {
        return SIZE;
    }

    @Override
    public EV3Type copy() {
        return new Data16(value);
    }

    @Override
    public void readFrom(InputStream inStream, int index) throws IOException {
        inStream.skip(index);
        int b0 = inStream.read();
        int b1 = inStream.read();
        setValue( b0 + (b1 << 8) );
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }
        Data16 data = (Data16) o;
        return value == data.value;
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }
}
